package com.ruoyi.system.service.impl;

import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;

import java.util.Properties;

public class SparkSQLMySQLQueryInsert {
    public static void main(String[] args) {
        // 创建 SparkSession 对象
        SparkSession spark = SparkSession.builder()
                .appName("SparkSQLMySQLQueryInsert")
                .master("local[*]")
                .getOrCreate();

        // 数据库连接信息
        String url = "jdbc:mysql://192.168.25.131:3306/ry";
        Properties properties = new Properties();
        properties.setProperty("user", "root");
        properties.setProperty("password", "123");
        properties.setProperty("driver", "com.mysql.cj.jdbc.Driver");

        // 执行 SQL 查询
        String sql = "select dept_id as user_id from sys_user";
        Dataset<Row> resultDF = spark.read()
                .jdbc(url, "(" + sql + ") AS subquery", properties);

        // 将结果插入到 users 表
        resultDF.write()
                .mode("append")
                .jdbc(url, "users", properties);

        // 停止 SparkSession
        spark.stop();
    }
}
